﻿Shader "Custom/Standard(OrderedDither)"
{
	Properties
	{
		_Color("Color", Color) = (1,1,1,1)
	}

	SubShader
	{
		Stencil
		{
			Ref 1
			Comp Always
			Pass Replace
		}

		Tags { "RenderType"="Opaque" }
		LOD 200
		
		CGPROGRAM
		#pragma surface surf Standard fullforwardshadows
		#pragma vertex vert
		#pragma target 3.0

		struct Input
		{
			float2 uv_MainTex;

			float4 screenPos;
		};

		fixed4 _Color;

		inline float Dither8x8Bayer(float value, float2 sceneUVs)
		{
			if (value <= 0)return -1;

			float2 px = sceneUVs;

			px = float2(fmod(px.x, 8), fmod(px.y, 8));

			const float dither[64] = {
				1, 49, 13, 61,  4, 52, 16, 64,
				33, 17, 45, 29, 36, 20, 48, 32,
				9, 57,  5, 53, 12, 60,  8, 56,
				41, 25, 37, 21, 44, 28, 40, 24,
				3, 51, 15, 63,  2, 50, 14, 62,
				35, 19, 47, 31, 34, 18, 46, 30,
				11, 59,  7, 55, 10, 58,  6, 54,
				43, 27, 39, 23, 42, 26, 38, 22 };
			int r = px.y * 8 + px.x;
			return value - (dither[r] - 1) / 63;
		}

		void surf (Input IN, inout SurfaceOutputStandard o)
		{
			float alpha = _Color.a;

			float2 clipScreen62 = (IN.screenPos.xy / IN.screenPos.w) * _ScreenParams.xy;
			clip(Dither8x8Bayer(alpha*1.2, clipScreen62));

			o.Albedo = 1;
		}

		void vert(inout appdata_full appdata, out Input o)
		{
			UNITY_INITIALIZE_OUTPUT(Input, o);

			float4 hpos = UnityObjectToClipPos(appdata.vertex);
			o.screenPos = hpos;
		}
		ENDCG
	}
	FallBack "Diffuse"
}
